package top.suven.base.http.admin.user.dao;

import top.suven.base.util.Ip2regionDbSearch;
import top.suven.base.common.util.Constant;
import org.apache.commons.lang.StringUtils;
import org.lionsoul.ip2region.DataBlock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName:
 * @Description:
 * @Author lixiangling
 * @Date 2018/8/27 15:53
 * @Copyright: (c) 2018 gc by https://www.gc.com.cn/
 * @Version : 1.0.0
 * --------------------------------------------------------
 * modifyer    modifyTime                 comment
 * <p>
 * --------------------------------------------------------
 */
@Component
public class UserJdbcDao {
    private Logger logger = LoggerFactory.getLogger(UserJdbcDao.class);
    @Autowired
    private DataSource dynamicDataSource;
//    @Autowired
//    private RedisClusterServer redisClusterServer;
    @Value("${ip2region.path}")
    private String ip2dbPath;

    public Map<String,Integer> getUserProvince(int modVal) {
        Map<String,Integer> retMap = new HashMap<String,Integer>();
        String sql = "select register_ip from rf_user where status='1' and mod(user_id,10)=? ";
        Connection conn = null;
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;
        try {
            conn = dynamicDataSource.getConnection();
            conn.setAutoCommit(false);
            preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setObject(1, modVal);
            preparedStatement.setFetchSize(1000);
            logger.debug("sql:{}", sql);
            logger.debug("param:{}", modVal);
            rs = preparedStatement.executeQuery();
            while (rs.next()) {
                String ip = rs.getString("register_ip");
                if(StringUtils.isBlank(ip)||ip.startsWith("192.168")){
                    continue;
                }
//                String region = redisClusterServer.get(String.format("%s%s", RedisKeys.USER_IP, ip));
//                if(StringUtils.isNotBlank(region)){
//                    String[] regions = region.split("|");
//                    retMap.put(regions[2], retMap.getOrDefault(regions[2], 0) + 1);
//                    continue;
//                }
                try {
                    //根据对应ip查询所属地市的id

                    //DbSearcher dbSearcher = Ip2regionDbSearch.getDbSearcher(ip2dbPath);
                    DataBlock dataBlock = Ip2regionDbSearch.getDbSearcher(ip2dbPath).btreeSearch(ip);
                    if (dataBlock == null || dataBlock.getCityId() == Constant.one) {
                        continue;
                    }
                    String[] regions = dataBlock.getRegion().split("\\|");
                    if (regions.length < 3) {
                        continue;
                    }
//                redisClusterServer.set(String.format("%s%s", RedisKeys.USER_IP, ip), dataBlock.getRegion().getBytes());
                    retMap.put(regions[2], retMap.getOrDefault(regions[2], 0) + 1);
                }catch (IOException e){
                    //logger.error("根据用户注册ip获取物理地址失败",e);
                }catch (Exception e){
                    //logger.error("获取用户地址失败",e);
                }
            }
        }catch (SQLException e){
            logger.error("获取用户注册ip失败",e);
        }catch (Exception e){
            logger.error("获取用户地址失败",e);
        }finally {
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {
                }
            }
            if(preparedStatement != null){
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                }
            }
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                }
            }
        }
        return retMap;
    }
}
